<!--
 @description 购物车-编辑折扣
 @fileName index.vue
 @author zengqiongying
 @created 2022/08/02 15:19:38
-->
<template>
  <Popup
    v-model="popShow"
    title="请手动输入折扣"
    @confirm="handleSubmit"
  >
    <div class="discount-cell">
      <van-field
        v-model="discount"
        type="number"
        label=""
        format-trigger="onBlur"
        :formatter="formatterDis"
        placeholder="请输入0-10之间的数字"
      />
      <span class="unit">折</span>
    </div>
    <div class="alert-msg">
      注意：原价为0的商品，不参与折扣
    </div>
  </Popup>
</template>

<script>
import Popup from '@/components/Popup'
import { modifyDiscount } from '@/apis/cart'
export default {
  name: 'CartDiscount',
  components: { Popup },
  props: {
    show: {
      type: Boolean,
      default: false
    },
    ids: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      discount: ''
    }
  },

  computed: {
    popShow: {
      set(val) {
        this.$emit('update:show', val)
      },
      get(val) {
        return this.show
      }
    }
  },
  watch: {

  },
  created() {

  },
  methods: {
    // 格式化折扣
    formatterDis(value) {
      if (value === '') return ''
      const val = Math.floor(value * 10) / 10
      if (val <= 0) {
        this.$toast('输入的折扣不能小于0')
        return 0
      } else if (val > 10) {
        this.$toast('输入折扣不能大于10')
        return 10
      }
      return val
    },
    handleSubmit() {
      const discount = `${this.discount || ''}`.trim()
      if (!discount || discount.length === 0) {
        this.$toast('请输入折扣')
        return
      }
      const val = Math.floor(discount * 10) / 10
      if (val <= 0 || val >= 10) {
        this.$toast('请输入0 到10 之间的数字')
        return false
      }
      const params = {
        discount: val,
        ids: this.ids
      }
      modifyDiscount(params).then(res => {
        if (res.success === 1) {
          this.$emit('success', params)
          this.$toast('折扣更新成功')
          this.popShow = false
        }
      }).catch(() => {

      })
    }
  }
}

</script>
<style lang='less' scoped>
.discount-cell{
  display: flex;
  justify-items: center;
  .unit{
    padding: 0 15px;
    line-height: 42px;
    color: #343640;
    font-size: 18px;
    font-weight: bold;
  }
  .van-field{
    flex: 1;
    height: 42px;
    border-radius: 12px;
    border: 2px solid #EFF2F7;
    box-sizing: border-box;
  }
}
.alert-msg{
  padding: 12px 0 22px;
  color: #F94B4B;
  line-height: 20px;
  font-size: 12px;
}
</style>
